package com.bstek.urule.console;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.util.ResourceUtils;

import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * @autor gehongbin
 * @date 4/27/22
 **/
public class FreemarkerUtils {

    Template temp;
    Map<String,Object> param = new HashMap<>();

    public FreemarkerUtils(String path) throws IOException {
        Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        cfg.setEncoding(Locale.CHINA, "utf-8");
        cfg.setDirectoryForTemplateLoading(ResourceUtils.getFile("classpath:xml"));
        this.temp = cfg.getTemplate(path);
    }

    public FreemarkerUtils data(String key, Object data) throws IOException{
        this.param.put(key, data);
        return this;
    }

    public String build() throws IOException, TemplateException {
        StringWriter sw = new StringWriter();
        temp.process(param, sw);
        return sw.toString();
    }
}
